const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin } = require('fabric-network');
const fs = require('fs');
const path = require('path');

async function enrollAdmin() {
  try {
    // Load the connection profile
    // console.log(typeof(path))

    const ccpPath = 'E:\\WorkSpace\\ETS\\config\\connection.json';
    const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
    const ccp = JSON.parse(ccpJSON);
    // console.log(ccpJSON);

    // /WorkSpace/ETS/config/
    // Create a new CA client for interacting with the Fabric CA server
    const caInfo = ccp.certificateAuthorities['ca.example.com'];
    console.log(caInfo.tlsCACerts.path);

    const caTLSCACertsPath = path.resolve(__dirname, caInfo.tlsCACerts.path);
    const caTLSCACerts = fs.readFileSync(caTLSCACertsPath);
    const ca = new FabricCAServices(caInfo.url, { trustedRoots: caTLSCACerts, verify: false }, caInfo.caName);

    // Create a new file system wallet
    const walletPath = path.resolve(__dirname, 'wallet');
    const wallet = new FileSystemWallet(walletPath);

    // Check if the admin user already exists in the wallet
    const adminExists = await wallet.exists('admin');
    if (adminExists) {
      console.log('An identity for the admin user "admin" already exists in the wallet');
      return;
    }

    // Enroll the admin user and import the identity into the wallet
    const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });
    const identity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
    wallet.import('admin', identity);
    console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
  } catch (error) {
    console.error(`Failed to enroll admin user: ${error}`);
    process.exit(1);
  }
}

enrollAdmin();
